# -*- coding: utf-8 -*-

"""
.. todo:: docstring


"""
from __future__ import print_function


# __all__ = [""]




import zlib
import base64

import pygame

# -----------------------------------------------------------------------------

def image_to_string(image, format='RGBA', level=9):
    """
    Converts the image into a compressed, base64 encoded string.
    """
    str_img = pygame.image.tostring(image, format)
    w, h = image.get_size()
    str_img = '|'.join((format, str(w), str(h), str_img))
    if level:
        str_img = zlib.compress(str_img, level)
    return base64.b64encode(str_img)


def string_to_image(input_str, flipped=False):
    """
    Converts a string encoded previously with :py:func:`image_to_string()` back to an image.
    """
    input_str = base64.b64decode(input_str)
    try:
        input_str = zlib.decompress(input_str)
    except:
        pass
    format, w, h, str_img = input_str.split('|', 3)
    size = (int(w), int(h))
    return pygame.image.fromstring(str_img, size, format, flipped)


# -----------------------------------------------------------------------------



#   http://www.akeric.com/blog/?p=720

def blur_surf(surface, amount_x, amount_y=None, border=None, background=(0, 0, 0, 0)):

    """
    From: http://www.akeric.com/blog/?p=720

    Blur the given surface by the given 'amount'.  Only values 1 and greater
    are valid.  Value 1 = no blur.

    """


    amount_y = amount_y or amount_x # use x value if y is not set

    if amount_x < 1.0:
        raise ValueError("Arg 'amount_x' must be greater than 1.0, passed in value is %s" % amt)
    if amount_y < 1.0:
        raise ValueError("Arg 'amount_y' must be greater than 1.0, passed in value is %s" % amt)

    width, height = surface.get_size()
    if border:
        width += 2 * border
        height += 2 * border
        border_surface = pygame.Surface((width, height), pygame.SRCALPHA)
        border_surface.fill(background)
        border_surface.blit(surface, (border, border))
        surface = border_surface

    scale_x = 1.0/float(amount_x)
    scale_y = 1.0/float(amount_y)
    min_pixel = 1
    scale_size = (max(min_pixel, width * scale_x), max(min_pixel, height * scale_y))
    # print '? scale', scale_x, scale_y, 'scale size:', scale_size

    # surf = pygame.transform.scale(surface, scale_size)
    surf = pygame.transform.smoothscale(surface, scale_size)
    return pygame.transform.smoothscale(surf, (width, height))

    # surf = pygame.transform.rotozoom(surface, 0, scale_x)
    # w, h = surf.get_size()
    # print 'new', width / float(w), 'amount', amount_x
    # return pygame.transform.rotozoom(surf, 0, width / float(w))
    # # return pygame.transform.rotozoom(surf, 0, amount_x)



# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
